from fastapi import FastAPI, Query # 导入fastapi的主入口FastAPI
from enum import Enum # 导入枚举类Enum
from typing import Union, Optional

from pydantic import BaseModel

app = FastAPI()  # 创建FastAPI应用实例

class SexModel(str, Enum): # 定义枚举类，用于区分性别 
    Male = "1" 
    Female = "2"

class UserModel(BaseModel):
    id: str
    name: str
    nick_name: str
    phone: str
    age: Union[int,None]=None
    sex: Union[SexModel,None] = None


@app.get("/") # 定义根路径的路由，就是网页上的地址
async def root(test:Optional[int]='1', item:Union[int,None]=None ): #      定义一个异步函数，返回一个json串
    return {"message": item}

@app.get("/items/{addr}") # 定义一个路径参数的路由
async def read_item(addr: str, name:Union[UserModel, None]=None): # 定义一个异步函数，参数为phone，类型为int
    return {**name.dict(), "addr": addr}

@app.post('/user/{dept}')
async def add_user(dept:str, user:UserModel, 
    q:str=Query(
        default=None,
        #alias="别名",
        title="字段标题",
        description="参数描述",
        min_length=3,
        max_length=50,
        lt=300,
        gt=2,
        pattern="^fixedquery$",
        deprecated=True,
        #regex="^fixedquery$",
    )):
    '''
    增加部门和用户
    '''
    return {'dept':dept,'q':q, **user.dict()}
    